/**
 * Description：实测值录入二维码 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.27
 */
const { reactive, ref } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
import { useExportExcel } from '../../../Scripts/hooks/useExportExcel.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useCheckResultQRCode() {
  const baseAPI = '../../../Ashx/InputCheckPointResultVue3PageHandler.ashx';
  const QRCodeBaseAPI = '../../../Ashx/CheckPointQRCodeVue3PageHandler.ashx'

  const checkResultQRCodeContainerRef = ref(null);//[流水卡信息]表格ref
  const checkResultQRCodeChildContainerRef = ref(null);//子序号批次表格ref
  const checkResultQRCodeCheckItemTableRef = ref(null);//检测项表格ref
  const checkResultQRCodeResultTableRef = ref(null);//检测项结果表格ref
  const checkItemResultScanTableRef = ref(null);//扫码结果表格ref

  let checkResultQRCodeObj = reactive({
    dialogVisible: false,
    tabObj: {
      container: 'container',
      checkitem: 'checkitem',
      childcontainer: 'childcontainer',
      checkresult: 'checkresult',
      inputZone: 'inputZone',
      importCheckPoint: 'importCheckPoint',
      uploadZone: 'uploadZone',
    },
    currentSelectInfo: {},//当前选中的报工批次
    containerList: [],//批次信息表格
    checkitemList: [],//检测项表格
    childContainerList: [],//子批次表格
    checkItemResultList: [],//已录入结果表格
    qrcodeList: [],//二维码列表
    checkResult: '',//检测结果
    checkItemResultScanList: [],//扫码结果表格
  });
  let currentUserInfo = {};// 当前登录用户信息

  let containerInfo = {};

  // 重置对话框数据
  function resetDialogData() {
    checkResultQRCodeObj.currentSelectInfo = {};
    checkResultQRCodeObj.containerList = [];
    checkResultQRCodeObj.checkitemList = [];
    checkResultQRCodeObj.childContainerList = [];
    checkResultQRCodeObj.checkItemResultList = [];
    checkResultQRCodeObj.qrcodeList = [];
    checkResultQRCodeObj.checkResult = '';
    checkResultQRCodeObj.checkItemResultScanList = [];
  }

  async function initCheckResultQRCodeDialogData(selectionRows, userInfo) {
    checkResultQRCodeObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    containerInfo = selectionRows[0];
    resetDialogData();
    await getContainerData(selectionRows);
  }

  // 查询子序号批次信息
  async function getContainerData(postData) {
    const { data, status: { msg } } = await useFetch({
      url: `../../../Ashx/InputCheckPointResultVue3PageHandler.ashx?actions=getContainerDataList`,
      data: { type: 'getContainerDataList', postData }
    });
    checkResultQRCodeObj.containerList = data.value.dtReportContainer;//流水卡信息表格
    checkResultQRCodeObj.childContainerList = data.value.dtChildContainer;//子批次表格
    checkResultQRCodeObj.currentSelectInfo = data.value.dtReportContainer[0];//【流水卡信息】表格默认选中第一行
    checkResultQRCodeContainerRef.value.setCurrentRow(data.value.dtReportContainer[0]);//【流水卡信息】默认选中第一条(高亮显示)
  }

  // [流水卡信息]表格选中行变更
  async function checkResultQRCodeCurrentChange(val) {
    if (!val) { return; }
    checkResultQRCodeObj.currentSelectInfo = val;
    const { containerid, workflowstepid, containerstepworkreportid, containertype } = checkResultQRCodeObj.currentSelectInfo;
    // 1.获取检测项
    await getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid: '' });
    await getQRCodeListData();//获取检测项二维码
    if (containertype === 3) {
      // 2.查询报工时选择的子批次号
      checkResultQRCodeChildContainerRef.value.clearSelection();//先清空选择
      // 过滤出报工时勾选的子批次，并选中
      const list = await getWorkreportChildContainer(containerstepworkreportid);
      checkResultQRCodeObj.childContainerList.forEach(row => {
        if (list.some(i => i.childcontainerid === row.childcontainerid)) {
          checkResultQRCodeChildContainerRef.value.toggleRowSelection(row, undefined)
        }
      });
    }
  }

  // 查询报工时选择的子批次
  async function getWorkreportChildContainer(containerstepworkreportid) {
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getWorkreportChildContainer`,
      data: { type: 'getWorkreportChildContainer', containerstepworkreportid }
    });
    return data.value;
  }

  // 查询检测项数据
  async function getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid }) {
    const { data, status: { msg } } = await useFetch({
      url: `../../../Ashx/InputCheckPointResultVue3PageHandler.ashx?actions=getCheckItemList`,
      data: {
        type: 'getCheckItemList',
        containerID: containerid,
        workFlowStepId: workflowstepid,
        containerStepWorkReportID: containerstepworkreportid,
        stepInfoID: stepinfoid,
      }
    });
    for (const i of data.value) {
      i.containerstepworkreportid = containerstepworkreportid;//缓存报工id
      i.containerid = containerid;//缓存批次id
      i.workflowstepid = workflowstepid;//缓存工序id
    }
    checkResultQRCodeObj.checkitemList = data.value;
  }

  // 检测项表格row点击事件
  function checkResultQRCodeCheckItemTableRowClick(row, column, event) {
    checkResultQRCodeCheckItemTableRef.value.clearSelection();
    checkResultQRCodeCheckItemTableRef.value.toggleRowSelection(row, undefined)
  }

  // 查询检测项录入结果
  async function getcheckResultQRCodeResultTableData(val) {
    const selections = checkResultQRCodeCheckItemTableRef.value.getSelectionRows();
    if (selections.length !== 1) {
      checkResultQRCodeObj.checkItemResultList = [];
      return;
    }
    const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = selections[0];
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getStepCheckPointResult`,
      data: {
        type: 'getStepCheckPointResult',
        childContainer: checkResultQRCodeChildContainerRef.value.getSelectionRows(),//勾选的子批次
        stepCheckPointId: stepcheckpointid,//检查项id
        containerId: containerid,//批次id
        containerStepWorkReportID: containerstepworkreportid//报工id
      }
    });
    checkResultQRCodeObj.checkItemResultList = data.value;
    checkResultQRCodeResultTableRef.value.toggleAllSelection();//检测结果表格默认全选
  }

  // 获取检测项二维码
  async function getQRCodeListData() {
    const childContainers = checkResultQRCodeChildContainerRef.value.getSelectionRows().map(m => m.childcontainerid).join(',');
    const selections = checkResultQRCodeCheckItemTableRef.value.getSelectionRows();//add by longb 2025-01-07
    const checkPoints =selections.length==0?checkResultQRCodeObj.checkitemList.map(u => u.stepcheckpointid).join(','):selections.map(u => u.stepcheckpointid).join(',');//modify by longb 2025-01-07
    const { data, status: { msg } } = await useFetch({
      url: `${QRCodeBaseAPI}?actions=getContainerQRCode`,
      data: {
        type: 'getContainerQRCode',
        containernames: checkResultQRCodeObj.containerList[0].containername,
        childContainers,//勾选的子批次
        checkPoints//所有检测项
      }
    });
    if (data.value) {
      checkResultQRCodeObj.qrcodeList = data.value;
    } else {
      ElMessage({ type: 'error', message: `${msg}`, grouping: true });
    }
  }

  // 【检测结果】文本框blur事件
  async function addQRCodeScanResult() {
    if (!checkResultQRCodeObj.checkResult) { return; }
    if (checkResultQRCodeObj.checkItemResultScanList.some(i => i.checkresult === checkResultQRCodeObj.checkResult)) {
      return ElMessage({ type: 'error', message: `检测结果已存在`, grouping: true });
    }
    checkResultQRCodeObj.checkItemResultScanList.push({ checkresult: checkResultQRCodeObj.checkResult });
    checkResultQRCodeObj.checkResult = '';
    checkItemResultScanTableRef.value.toggleAllSelection();
  }

  // 【提交】按钮
  function checkResultQRCodeSubmit() {
    const checkItemsSelections = checkResultQRCodeCheckItemTableRef.value.getSelectionRows();
    if (checkItemsSelections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
    }
    const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = checkItemsSelections[0];

    const selections = checkItemResultScanTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选扫码录入的结果`, grouping: true });
    }

    ElMessageBox.confirm(`你确认要提交吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${QRCodeBaseAPI}?actions=saveQRCode`,
        data: {
          type: 'saveQRCode',
          containerStepWorkReportID: containerstepworkreportid,
          saveType: '2',
          employeename: currentUserInfo.employeename,
          postData: selections,
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `提交成功`, grouping: true });
        checkResultQRCodeObj.checkItemResultScanList = [];
      } else {
        ElMessage({ type: 'error', message: `${msg}`, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  // 生成一个检测结果字符串
  async function generateQRCodeString() {
    const { containerno, productname, specno, containername, realcontainerno } = containerInfo;
    const { data, status: { msg } } = await useFetch({
      url: `${QRCodeBaseAPI}?actions=generateQRCodeString`,
      data: {
        type: 'generateQRCodeString',
        togetherflag: realcontainerno,
        containername,
        productname,
        specno
      }
    });
    ElMessage({ type: 'success', message: `${data.value}`, grouping: true });
  }

  return {
    checkResultQRCodeObj,
    initCheckResultQRCodeDialogData,
    checkResultQRCodeContainerRef,//[流水卡信息]表格ref
    checkResultQRCodeChildContainerRef,//子序号批次表格ref
    checkResultQRCodeCheckItemTableRef,//检测项表格ref
    checkResultQRCodeResultTableRef,//检测项结果表格ref
    checkResultQRCodeCheckItemTableRowClick,//检测项表格row点击事件
    getcheckResultQRCodeResultTableData, //查询检测项录入结果
    getQRCodeListData,//获取二维码
    checkResultQRCodeSubmit,//确认提交
    addQRCodeScanResult,
    checkItemResultScanTableRef,//扫码结果表格ref
    generateQRCodeString,
    checkResultQRCodeCurrentChange
  };
}